<template>
  <div class="material-wrap">
    <div class="bg-box">
      <img :src="avatar?avatar:require('./avatar.png')" class="avatar" onclick="return false"/>
      <input type="file" class="photo" @change="changeImage($event)"
             accept="image/*"/>
      <div class="nickname">{{username}}</div>
    </div>
    <div class="content-box">
      <span class="title">昵称：</span>
      <input type="text" v-model="nickname" placeholder="请输入昵称" maxlength="11" class="name" @blur="inputBlur"/>
    </div>
    <div class="content-box">
      <span class="title">性别：</span>
      <div class="mui-radio mui-left">
        <input type="radio" name="radio-sex" :checked="man" @click="check(1)">
        <label>男</label>
      </div>
      <div class="mui-radio mui-left">
        <input type="radio" name="radio-sex" :checked="woman" @click="check(2)">
        <label>女</label>
      </div>
    </div>
    <div class="content-box">
      <span class="title">生日：</span>
      <datetime format="YYYY-MM-DD" v-model="birthday" class="birthday" @on-hide="onHide"
                placeholder="请选择生日" :end-date="date"></datetime>
      <div class="back-box"><img src="./back.png" class="back" onclick="return false"/></div>
    </div>
    <div class="content-box">
      <span class="title">情感状态：</span>
      <popup-picker :data="marryList" v-model="marry" class="marryPop" @on-hide="onHide"></popup-picker>
      <div class="back-box"><img src="./back.png" class="back" onclick="return false"/></div>
    </div>
    <div class="content-box">
      <span class="title">曾任职工作：</span>
      <popup-picker :data="plantList1" :columns="2" v-model="work" class="marryPop" placeholder="请选择曾任职工作" ref="picker1"
                    @on-hide="onHide1"></popup-picker>
      <div class="back-box"><img src="./back.png" class="back" onclick="return false"/></div>
    </div>
    <div class="content-box">
      <span class="title">工作年限：</span>
      <popup-picker :data="yearList" v-model="workYear" class="marryPop" @on-hide="onHide"></popup-picker>
      <div class="back-box"><img src="./back.png" class="back" onclick="return false"/></div>
    </div>
    <div class="content-box">
      <span class="title">理想薪资：</span>
      <popup-picker :data="moneyList" v-model="money" class="marryPop" @on-hide="onHide"
                    placeholder="请选择理想薪资"></popup-picker>
      <div class="back-box"><img src="./back.png" class="back" onclick="return false"/></div>
    </div>
    <div class="content-box">
      <span class="title">理想岗位：</span>
      <popup-picker :data="plantList2" :columns="2" v-model="post" class="marryPop" placeholder="请选择理想岗位" ref="picker2"
                    @on-hide="onHide2"></popup-picker>
      <div class="back-box"><img src="./back.png" class="back" onclick="return false"/></div>
    </div>

    <div class="btn-box">
      <button class="btn" type="button" @click="saveProfile">保存</button>
    </div>
  </div>
</template>

<script>
  import {convertBase64ToBlob, getBase64, getSessionStore, formatDate} from "../../common/js/util"
  import * as qiniu from 'qiniu-js'
  import {baseUrl} from "../../common/js/env"
  import {PopupPicker, Picker, Datetime} from 'vux'

  export default {
    data() {
      return {
        avatar: "",
        nickname: "",
        username: this.$route.query.nickname,
        birthday: this.$route.query.birthday,
        gender: "",
        man: "",
        woman: "",
        userSign: "",
        marryList: [['单身', '未婚', '已婚', '保密']],
        yearList: [['1年', '2年', '3年', '4年', '5年', '6+年']],
        moneyList: [['3k~4k', '4k~5k', '5k~6k', '6k~7k', '7k~8k', '8k~9k', '10+K']],
        marry: [],
        work: [],
        workYear: [],
        money: [],
        post: [],
        plantList1: [],
        plantList2: [],
        date: "",
      }
    },
    mounted() {
      this.date = formatDate(new Date(), "yyyy-MM-dd");
      this.nickname = this.$route.query.nickname;//昵称
      this.avatar = getSessionStore("avatar");//头像
      this.gender = this.$route.query.gender;//性别
      if (this.gender == 0 || this.gender == 1) {
        this.man = true;
      } else {
        this.woman = true;
      }
      let status = this.$route.query.marry;//情感状态
      if (status == 0) {
        this.marry.push("保密");
      } else if (status == 1) {
        this.marry.push("未婚");
      } else if (status == 2) {
        this.marry.push("已婚");
      } else {
        this.marry.push("单身");
      }
      if (this.$route.query.work) {
        this.work.push(this.$route.query.work);//曾任职工作
      }
      if (this.$route.query.post) {
        this.post.push(this.$route.query.post);//理想岗位
      }
      this.workYear.push(this.$route.query.workYear + '年');//工作年限
      if (this.$route.query.money) {
        this.money.push(this.$route.query.money);//理想薪资
      }
      let base64 = require('js-base64').Base64;
      this.userSign = base64.decode(sessionStorage.getItem("user_sign"));
      this.queryPostList();
    },
    methods: {
      inputBlur() {
        window.scrollTo(0, 0)
      },
      checkNickname() {//校验昵称
        let nickname = this.nickname;
        if (nickname == "") {
          this.$vux.toast.text("请输入昵称", "middle");
          return;
        } else if (nickname.length > 11) {
          this.$vux.toast.text("昵称长度限制在11位以内", "middle");
          return;
        }
        return true;
      },
      check(index) {
        this.gender = index;
      },
      changeImage(e) {//上传图片到七牛云
        if (e.target.files.length > 0) {
          getBase64(e.target, (url) => {
            this.avatar = 'data:image/png;base64,' + url;//显示图片

            //获取uploadToken
            this.axios.get(baseUrl + "/platform/get_token?sgin=" + this.userSign).then((res) => {
              let resultObj = res.data;
              let file = convertBase64ToBlob(this.avatar); //Blob 对象，上传的文件
              let key = null; // 上传后文件资源名以设置的 key 为主，如果 key 为 null 或者 undefined，则文件资源名会以 hash 值作为资源名。
              let config = {
                useCdnDomain: true, //表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
                region: qiniu.region.z2 // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域};
              };

              let putExtra = {
                fname: "", //文件原文件名
                params: {}, //用来放置自定义变量
                mimeType: null //用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
              };
              let observable = qiniu.upload(file, key, resultObj.data, putExtra, config);

              observable.subscribe({
                next: (res) => {//主要用来展示进度
                  let total = res.total;
                },
                error: (err) => {//失败报错信息
                  this.$vux.toast.text("图片上传失败，请重试", "middle");
                },
                complete: (res) => {//接收成功后返回的信息
                  this.avatar = "http://pic.lanpin123.com/" + res.hash;
                }
              })
            })
          })
        }
      },
      queryPostList() {//查询理想岗位及曾任职工作
        this.axios.get(baseUrl + "/userMaterial/select_mechanism").then((res) => {
          let resultObj = res.data;
          if (resultObj.code == 0) {
            for (let i = 0, length = resultObj.data.length; i < length; i++) {
              let name = resultObj.data[i].mechanismTypeName;//厂名
              let value = String(resultObj.data[i].id);
              let obj1 = {
                name: name,
                value: value
              };
              this.plantList1.push(obj1);
              this.plantList2.push(obj1);
              let list = resultObj.data[i].workTypeList;
              for (let k = 0, length = list.length; k < length; k++) {
                let key = list[k].workTypeName;
                let parent = String(list[k].mechanismTypeId);
                let obj2 = {
                  name: key,
                  value: key,
                  parent: parent
                };
                this.plantList1.push(obj2);
                this.plantList2.push(obj2);
              }
            }
          } else {
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch((error) => {
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      onHide(type) {
        if (type) {
          this.changeGender();
        }
      },
      onHide1(type) {
        if (type) {
          this.work = [];
          if (this.$refs.picker1 && this.$refs.picker1.getNameValues()) {
            let arr = this.$refs.picker1.getNameValues().split(" ");
            this.work.push(arr[0] + "-" + arr[1]);
          }
          this.changeGender();
        }
      },
      onHide2(type) {
        if (type) {
          this.post = [];
          if (this.$refs.picker2 && this.$refs.picker2.getNameValues()) {
            let arr = this.$refs.picker2.getNameValues().split(" ");
            this.post.push(arr[0] + "-" + arr[1]);
          }
          this.changeGender();
        }
      },
      saveProfile() {//保存个人资料
        if (this.checkNickname()) {
          //修改个人资料
          this.$vux.loading.show({
            text: '加载中',
          });

          let number = this.changeNumber();
          let year = this.workYear.toString();
          let data = {
            "type": 0,
            "birthday": this.birthday,
            "ideal_money": this.money.toString(),
            "ideal_post": this.post.toString(),
            "marry_status": number,
            "work_type": this.work.toString(),
            "work_years": parseInt(year.replace("年", ""))
          };
          this.axios.post(baseUrl + "/userMaterial/saveOrUpdate?sgin=" + this.userSign + "&userName=" + this.nickname + "&userSex=" + this.gender + "&userUrl=" + this.avatar, data).then((res) => {
            let resultObj = res.data;
            this.$vux.loading.hide();
            if (resultObj.code == 0 && resultObj.data == 1) {
              setTimeout(() => {
                this.$router.push('/mine');
              }, 100);
            } else {
              this.$vux.toast.text(resultObj.msg, "middle");
              return;
            }
          }).catch(() => {
            this.$vux.loading.hide();
            this.$vux.toast.text("网络异常", "middle");
          });
        }
      },
      changeNumber() {
        let temp = this.marry.toString();
        if (temp == "保密") {
          return 0;
        } else if (temp == "未婚") {
          return 1;
        } else if (temp == "已婚") {
          return 2;
        } else {
          return 3;
        }
      },
      changeGender() {
        if (this.gender == 1) {
          this.man = true;
          this.woman = false;
        } else {
          this.man = false;
          this.woman = true;
        }
      }
    },
    components: {
      PopupPicker,
      Picker,
      Datetime
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../common/stylus/mixin.styl"
  @import "../../../static/css/mui.min.css"

  .material-wrap
    wh(100%, 100%)
    .bg-box
      fj(center, center)
      flex-direction: column
      margin: 0 auto
      margin-top: 0.04rem
      wh(94%, 3.987rem)
      bg-image("./bg.png", 100%, 100%)
      .avatar
        wh(1.587rem, 1.587rem)
        border-radius: 100%
      .photo
        wh(1.587rem, 1.587rem)
        position: absolute
        opacity: 0
        -ms-filter: 'alpha(opacity=0)'
        z-index: 999
        margin: 0 auto
        top: 0.945rem
        background: #6d6d72
      .nickname
        text-align: center
        width: 90%
        padding-top: 0.213rem
        size-color(0.4rem, rgba(255, 255, 255, 1))
        font-weight: 500
        ellipsis()
    .content-box
      display: flex
      align-items: center
      margin-left: auto
      wh(96.26%, 1.2rem)
      border-bottom: 0.013rem solid rgba(230, 230, 230, 1)
      size-color(0.4rem, rgba(102, 102, 102, 1))
      font-weight: 500
      .title
        padding-right: 0.25rem
      .birthday
        width: 60%
        color: rgba(102, 102, 102, 1)
      .birthday >>> .weui-cell__ft
        text-align: left
      .marryPop
        display: flex
        justify-content: flex-start
        width: 60%
      .marryPop >>> .vux-tap-active
        width: 100%
      .mui-left
        width: 20%
        display: flex
        justify-content: center
        align-items: center
      .name
        width: 80%
        height: 0.6rem
        line-height: 0.6rem
        size-color(0.4rem, rgba(102, 102, 102, 1))
      .back-box
        margin-left: auto
        margin-right: 0.4rem
        .back
          wh(0.213rem, 0.373rem)
    .btn-box
      fj(center, center)
      margin-top: 0.28rem
      padding-bottom: 0.28rem
      .btn
        wh(92.53%, 1.333rem)
        background: rgba(60, 175, 255, 1)
        border-radius(0.107rem)
        size-color(0.48rem, rgba(255, 255, 255, 1))
</style>
